<template>
  <view class="chat-container"> 
			<uni-notice-bar show-icon scrollable
				text="uni-app 版正式发布，开发一次，同时发布iOS、Android、H5、微信小程序、支付宝小程序、百度小程序、头条小程序等7大平台。" /> 
    <view class="content">
      <swiper class="swiper-box" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
        <swiper-item v-for="(item, index) in info" :key="index">
          <view :class="item.colorClass" class="swiper-item">
            <image class="image" :src="item.url" mode="aspectFill" />
          </view>
        </swiper-item>
      </swiper>
      <view class="article-card">
        <view class="article-header">
          精选头条
        </view>
        <view class="article-list">
          <view v-for="(title, index) in articles" :key="index" class="article-item">
            {{ title }}
          </view>
        </view>
      </view>
    </view>
    <view class="input-container">
      <input class="input-message" type="text" v-model="inputMessage" @input="onKeyInput" placeholder="请输入消息..."
        @confirm="handleSend" />
      <text class="uni-icon" v-if="showClearIcon" @click="clearIcon">&#xe434;</text>
      <button class="send-button" @click="handleSend">发送</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      indicatorDots: true,
      autoplay: true,
      interval: 2000,//切换的间隔时间
      duration: 500,//滑动动画时长
      image: '/static/brick.png',
      info: [{
        colorClass: 'uni-bg-red',
        url: '/static/brick.png',
        content: '内容 A'
      },
      {
        colorClass: 'uni-bg-green',
        url: '/static/logo.png',
        content: '内容 B'
      },
      {
        colorClass: 'uni-bg-blue',
        url: '/static/brick.png',
        content: '内容 C'
      }
      ],
      articles: [
        '高考政策调整',
        '志愿填报',
        '考试时间安排'
      ],
      chatId: '',
      user_unique_id: 'cqpk1t0nsmmkruf9g7m0',
      timer: null,
      showClearIcon: false,
      firstText: false, 
      inputMessage: '', 
      currentText: '',
      messages:[],
      title: '',
      token: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTcyODgwMDg3NiwiaWF0IjoxNzI4Nzk5OTc2LCJqdGkiOiJjczVtOXE2bTFmMDliNGw0bmU2MCIsInR5cCI6ImFjY2VzcyIsImFwcF9pZCI6ImtpbWkiLCJzdWIiOiJjcXBrMXQwbnNtbWtydWY5ZzdtMCIsInNwYWNlX2lkIjoiY3FwazF0MG5zbW1rcnVmOWc3bGciLCJhYnN0cmFjdF91c2VyX2lkIjoiY3FwazF0MG5zbW1rcnVmOWc3bDAifQ.zKOrCkXFGXWB2LLtBb9UGL-7phOPlgpMUjHuXoSZO9ERhIqCXqQns6ZEtL8o_L8EQkomMU6Jui1O9p0j2-_Q3Q',
      refreshToken: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTczNjU3NTk3NiwiaWF0IjoxNzI4Nzk5OTc2LCJqdGkiOiJjczVtOXE2bTFmMDliNGw0bmU2ZyIsInR5cCI6InJlZnJlc2giLCJhcHBfaWQiOiJraW1pIiwic3ViIjoiY3FwazF0MG5zbW1rcnVmOWc3bTAiLCJzcGFjZV9pZCI6ImNxcGsxdDBuc21ta3J1ZjlnN2xnIiwiYWJzdHJhY3RfdXNlcl9pZCI6ImNxcGsxdDBuc21ta3J1ZjlnN2wwIn0.azWgqL1SX52pqhLRKbOqq--etNzGneRzm9zu8miPuIFULWMvgiW7BQyqoCcu9e0yPeoY8VIE0Oj3LTtdSy6giw'
    };
  },
  unmounted() {
    clearInterval(this.timer)
  }, created() {
    this.timer = setInterval(() => {
      const timeStamp = Date.now()
      const req = [{
        events: [{ event: "_be_active", params: { start_time: timeStamp, end_time: timeStamp, url: "https://kimi.moonshot.cn/chat/cs3sfnalve9uar25glfg", referrer: "", title: "Kimi.ai - 帮你看更大的世界", event_index: 1728696765149 }, local_time_ms: 1728698913706, is_bav: 1, ab_sdk_version: "20183260, 20169060, 20170220, 20151149, 20145781, 20142879, 290769, 298062", session_id: "18d0403e- 0767 - 4980 - a5c8 - df382fb69cf0" }], user: { user_unique_id: this.userUniqueId, web_id: "7400330085250656769" }, header: { app_id: 20001731, os_name: "windows", os_version: "10", device_model: "Windows NT 10.0", language: "zh - CN", platform: "web", sdk_version: "5.1.12_tob", sdk_lib: "js", timezone: 8, tz_offset: -28800, resolution: "2049x1152", browser: "Microsoft Edge", browser_version: "129.0.0.0", referrer: "", referrer_host: "", width: 2049, height: 1152, screen_width: 2049, screen_height: 1152, custom: {} }, local_time: timeStamp, verbose: 1
      }]
      uni.request({
        url: 'https://gator.volces.com/list',
        method: 'POST',
        data: req,
        header: { 'Connection': 'keep-alive', 'Content-type': 'application/json; charset=UTF-8' },
        success: (res) => {
          console.log('keep alive list:', res)
          if (res.statusCode != 200) {
            clearInterval(this.timer)
          }
        },
      })
    }, 60000);
  },
  onHide() {
    const chatid = uni.getStorageSync('chatId')
    console.log("onhide:", chatid)
    if (chatid) {
      this.chatId = chatid
    } 

  },
  mounted() {
    const chatid = uni.getStorageSync('chatId')
    console.log("mounted:", chatid)
    const access_token = uni.getStorageSync('access_token');
    if (access_token) {
      this.token = access_token;
    }
    const refresh_token = uni.getStorageSync('refresh_token');
    if (refresh_token) {
      this.refreshToken = refresh_token;
    }
  }, methods: {
    refreshUserToken() {
      uni.request({
        method: 'GET', url: 'https://kimi.moonshot.cn/api/auth/token/refresh',
        header: { "Content-Type": "application/json", Authorization: `Bearer ${this.refreshToken}` },
        success: (res) => {
          console.log('refresh:', this.refreshToken)
          if (res.statusCode == 200) {
            this.token = res.data.access_token;
            this.refreshToken = res.data.refresh_token
            uni.setStorageSync('access_token', this.token);
            uni.setStorageSync('refresh_token', this.refreshToken); 
            const params = {
              "name": "未命名会话",
              "is_example": false,
              "enter_method": "new_chat",
              "kimiplus_id": "kimi"
            };
            uni.request({
              url: 'https://kimi.moonshot.cn/api/chat',
              method: 'POST',
              data: params,
              header: {Authorization: `Bearer ${this.token}`},
              success(res) {
                if (res.statusCode == 200) {
                  uni.setStorageSync("chatId", res.data.id);  
                }
              } 
            })

          } else {

            uni.showToast({
              title: "登录过期,请重新登录",
              icon: "none",
            });
            uni.redirectTo({ url: '/pages/login/login' })
          }
        },
        fail: (fail) => {
          uni.showToast({
            title: "登录过期,请重新登录",
            icon: "none",
          });
          uni.redirectTo({ url: '/pages/login/login' })
        },
      });
    },
    keepConnection() {
      const timeStamp = Date.now()

      const req = [{
        events: [{ event: "_be_active", params: { start_time: timeStamp, end_time: timeStamp, url: "https://kimi.moonshot.cn/chat/cs3sfnalve9uar25glfg", referrer: "", title: "Kimi.ai - 帮你看更大的世界", event_index: 1728696765149 }, local_time_ms: 1728698913706, is_bav: 1, ab_sdk_version: "20183260, 20169060, 20170220, 20151149, 20145781, 20142879, 290769, 298062", session_id: "18d0403e- 0767 - 4980 - a5c8 - df382fb69cf0" }], user: { user_unique_id: this.userUniqueId, web_id: "7400330085250656769" }, header: { app_id: 20001731, os_name: "windows", os_version: "10", device_model: "Windows NT 10.0", language: "zh - CN", platform: "web", sdk_version: "5.1.12_tob", sdk_lib: "js", timezone: 8, tz_offset: -28800, resolution: "2049x1152", browser: "Microsoft Edge", browser_version: "129.0.0.0", referrer: "", referrer_host: "", width: 2049, height: 1152, screen_width: 2049, screen_height: 1152, custom: {} }, local_time: timeStamp, verbose: 1
      }]
      uni.request({
        url: 'https://gator.volces.com/list',
        method: 'POST',
        data: req,
        header: { 'Connection': 'keep-alive', 'Content-type': 'application/json; charset=UTF-8' },
        success: (res) => {
          console.log('keep alive list:', res)
          if (res.statusCode != 200) {
            clearInterval(this.timer)
          }
        },
      })
    },
    onKeyInput(event) {

      if (event.target.value.trim) {
        const instance = { "offset": 0, "size": 10, "query": event.target.value }
        console.log(' instance data:', instance)

        uni.request({
          url: 'https://kimi.moonshot.cn/api/prompt-snippet/instance',
          data: instance,
          method: 'POST',
          header: { "Content-Type": "application/json", Authorization: `Bearer ${this.token}` },
          success: (res) => {
            console.log('instance success:', res)
            if (res.statusCode != 200) {
              this.refreshUserToken()
            }

            this.keepConnection()

          },
          fail: (fail) => {
          },
        })

      }
    },
    clearIcon() {
      this.inputMessage = '';
      this.showClearIcon = false;
    },
    clearInput(event) {
      this.inputMessage = event.detail.value;
      if (event.detail.value.length > 0) {
        this.showClearIcon = true;
      } else {
        this.showClearIcon = false;
      }
    },
    handleSend() {
      this.keepConnection()
      if (this.inputMessage.trim()) {    
    
          uni.redirectTo({
            url:`/pages/chat/newSession?message=${this.inputMessage}`
          })
      }
    },

    getArticles(msg) {
      this.keepConnection()
      if (msg.trim()) { 
        const data = {
          messages: [{ role: "user", content: msg }],
          use_search: false,
          extend: { sidebar: true },
          kimiplus_id: "kimi",
          use_research: false,
          refs: [],
        }; 
        const chatid = uni.getStorageSync('chatId')
        const requestTask = uni.request({
          url: `https://kimi.moonshot.cn/api/chat/${chatid}/completion/stream`,
          method: "POST",
          header: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${this.token}`,
          },
          data: data,
          responseType: "text",
          enableChunked: true, // 启用分块接收
          success: (response) => {
            console.log('resp:', response)
            if (response.statusCode == 404) {
              uni.showToast({
                title: "会话过期,请重新登录",
                icon: "none",
              });
              uni.redirectTo({ url: '/pages/login/login' })
            } else if (response.statusCode != 200) {
              this.refreshUserToken()
            }
          },
          fail: (error) => {
            console.error("Failed to send message:", error);
          },
          complete: (com) => {
          }
        });

        requestTask.onHeadersReceived((res) => {
          console.log("header:", res)
        });

        requestTask.onChunkReceived((res) => {
          const uint8Array = new Uint8Array(res.data);
          let text = String.fromCharCode.apply(null, uint8Array);
          text = decodeURIComponent(escape(text))
          // 解析接收到的数据块
          this.processChunk(text);
        });
      }
    },

    processChunk(chunkData) {
      const lines = chunkData.split("\n");

      lines.forEach((line) => {
        if (line.trim()) {
          try {
            const jsonObj = JSON.parse(line.substring(6)); // 移除 "data:" 前缀
            const { text, content, error, event } = jsonObj;

            if (content) {
              this.title = content; // 追加到当前文本
            }

            if (event == "cmpl" && text) { 
              this.currentText += text; // 追加到当前文本
              if (this.firstText) {
                this.firstText = false;
                this.messages.push({ content: text, isUser: false, id: `msg-${this.messages.length}` }) 
              } else {

                this.messages[this.messages.length - 1] = { content: this.currentText, isUser: false, id: `msg-${this.messages.length}` }

              }
            } else if (error) {
              const { message } = error;

              this.currentText += message; // 追加到当前文本
            } else if (event == 'all_done') {

              console.log("test", this.currentText)
            } else {
            }

          } catch (error) {
            console.error("Error parsing JSON:", error);
          }
        }
      });
    }

  }
}
</script>


<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7; /* 淡白色背景 */
  padding: 10px;
}

.content { 
  flex: 1;
  overflow: auto;
}

.swiper-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80%;
  height: 200px; /* Adjust the height as needed */
  margin: 0 auto;
  overflow: hidden;
}

.swiper-item {  
  display: flex;
  justify-content: center;
  align-items: center;
  width: 90%;
  height: 100%;
}

.image {
  width: 100%;
  height: 100%; 
  border-radius: 8px; /* 图片圆角 */
  object-fit: cover; /* 如果图片比例不匹配容器，裁剪并填充容器 */
}

.article-card {
  background-color: #fff; /* 白色背景 */
  border-radius: 16px;
  padding: 10px;
  margin-top: 10px;
}

.article-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.article-list { 
}

.article-item {
  padding: 2px 0;
}

.input-container {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-top: 1px solid #ddd;
  /* padding: 5px; */
  position: absolute;
  bottom: 0;
  width: 100%;
}

.input-message {
  flex: 1; 
  border-radius: 4px;
  border: 1px solid #ffffff;
  margin-right: 10px;
  font-size: 16px;
}

.send-button {
  padding: 10px 20px;
  margin-right: 10px;
  background-color: #3faded;
  color: #fff;
  border-radius: 8px;
  border: none;
  font-size: 16px;
  line-height: 40px;
  height: 40px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-message::placeholder {
  font-size: 16px;
  color: #aaa;
}

.uni-icon {
  font-family: 'uni-icons';
}
</style>